/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.stylefeng.guns.sys.core.exception.aop;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.exception.AuthException;
import cn.stylefeng.guns.base.auth.exception.PermissionException;
import cn.stylefeng.guns.base.auth.exception.enums.AuthExceptionEnum;
import cn.stylefeng.guns.sys.core.exception.BizCheckException;
import cn.stylefeng.guns.sys.core.exception.InvalidKaptchaException;
import cn.stylefeng.guns.sys.core.exception.enums.BizExceptionEnum;
import cn.stylefeng.guns.sys.core.log.LogManager;
import cn.stylefeng.guns.sys.core.log.factory.LogTaskFactory;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import cn.stylefeng.roses.kernel.model.response.ErrorResponseData;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import static cn.stylefeng.roses.core.util.HttpContext.getIp;
import static cn.stylefeng.roses.core.util.HttpContext.getRequest;

/**
 * 全局的的异常拦截器（拦截所有的控制器）（带有@RequestMapping注解的方法上都会拦截）
 *
 * @author fengshuonan
 * @date 2016年11月12日 下午3:19:56
 */
@ControllerAdvice
@Order(-100)
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 请求错误-没有该资源
     */
    int SC_NOT_FOUND = HttpStatus.NOT_FOUND.value();

    /**
     * 缺少必要的参数
     */
    int SC_BAD_REQUEST = HttpStatus.BAD_REQUEST.value();
    /**
     * 请求方式不支持
     */
    int SC_METHOD_NOT_ALLOWED = HttpStatus.METHOD_NOT_ALLOWED.value();

    public static final String KEY_MESSAGE = "message";

    public static final String KEY_CODE = "code";

    public static final HttpHeaders httpHeaders= new HttpHeaders();
    static {
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
    }

    /**
     * 参数校验错误
     *
     * @author fengshuonan
     * @Date 2020/2/5 11:50 下午
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ErrorResponseData handleError(MissingServletRequestParameterException e) {
        log.warn("Missing Request Parameter", e);
        String message = String.format("Missing Request Parameter: %s", e.getParameterName());
        return new ErrorResponseData(400, message);
    }

    /**
     * 参数校验错误
     *
     * @author fengshuonan
     * @Date 2020/2/6 10:18 上午
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ErrorResponseData handleError(MethodArgumentTypeMismatchException e) {
        log.warn("Method Argument Type Mismatch", e);
        String message = String.format("Method Argument Type Mismatch: %s", e.getName());
        return new ErrorResponseData(400, message);
    }

    /**
     * 参数校验错误
     *
     * @author fengshuonan
     * @Date 2020/2/6 10:19 上午
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ErrorResponseData handleError(MethodArgumentNotValidException e) {
        log.warn("Method Argument Not Valid", e);
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String message = String.format("%s:%s", error.getField(), error.getDefaultMessage());
        return new ErrorResponseData(400, message);
    }

    /**
     * 参数校验错误异常
     *
     * @author fengshuonan
     * @Date 2020/2/6 9:49 上午
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ErrorResponseData handleError(BindException e) {
        log.warn("Bind Exception", e);
        FieldError error = e.getFieldError();
        String message = String.format("%s:%s", error.getField(), error.getDefaultMessage());
        return new ErrorResponseData(400, message);
    }

    /**
     * 参数校验错误异常
     *
     * @author fengshuonan
     * @Date 2020/2/8 12:20
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ErrorResponseData handleError(ConstraintViolationException e) {
        log.warn("Constraint Violation", e);
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        ConstraintViolation<?> violation = violations.iterator().next();
        String path = ((PathImpl) violation.getPropertyPath()).getLeafNode().getName();
        String message = String.format("%s:%s", path, violation.getMessage());
        return new ErrorResponseData(400, message);
    }

    /**
     * 参数校验错误异常
     *
     * @author fengshuonan
     * @Date 2020/2/6 9:49 上午
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ErrorResponseData handleError(HttpMessageNotReadableException e) {
        log.warn("HttpMessageNotReadableException ", e);
        String message = String.format("HttpMessageNotReadableException:%s", e.getMessage());
        return new ErrorResponseData(400, message);
    }

    /**
     * 认证异常--认证失败（账号密码错误，账号被冻结，token过期等）
     *
     * @author fengshuonan
     * @Date 2020/2/6 11:14 上午
     */
    @ExceptionHandler(AuthException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public ErrorResponseData unAuth(AuthException e) {
        return new ErrorResponseData(e.getCode(), e.getMessage());
    }

    /**
     * 认证异常--没有访问权限
     *
     * @author fengshuonan
     * @Date 2020/2/6 11:14 上午
     */
    @ExceptionHandler(PermissionException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public ErrorResponseData permissionExpection(PermissionException e) {
        return new ErrorResponseData(e.getCode(), e.getMessage());
    }

    /**
     * 验证码错误异常
     *
     * @author fengshuonan
     * @Date 2020/2/6 11:14 上午
     */
    @ExceptionHandler(InvalidKaptchaException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ErrorResponseData credentials(InvalidKaptchaException e) {
        String username = getRequest().getParameter("username");
        LogManager.me().executeLog(LogTaskFactory.loginLog(username, "验证码错误", getIp()));
        return new ErrorResponseData(AuthExceptionEnum.VALID_CODE_ERROR.getCode(), AuthExceptionEnum.VALID_CODE_ERROR.getMessage());
    }

    /**
     * 拦截业务异常
     *
     * @author fengshuonan
     * @Date 2020/2/6 11:14 上午
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ErrorResponseData bussiness(ServiceException e) {
        log.error("业务异常:", e);
        if (LoginContextHolder.getContext().hasLogin()) {
            LogManager.me().executeLog(LogTaskFactory.exceptionLog(LoginContextHolder.getContext().getUserId(), e));
        }
        getRequest().setAttribute("tip", e.getMessage());
        return new ErrorResponseData(e.getCode(), e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     *
     * @author fengshuonan
     * @Date 2020/2/6 11:15 上午
     */
    @ExceptionHandler(Throwable.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ErrorResponseData notFount(Throwable e) {
        log.error("运行时异常:", e);
        if (LoginContextHolder.getContext().hasLogin()) {
            LogManager.me().executeLog(LogTaskFactory.exceptionLog(LoginContextHolder.getContext().getUserId(), e));
        }
        String message = String.format("服务器未知运行时异常: %s", e.getMessage());
        getRequest().setAttribute("tip", message);
        return new ErrorResponseData(BizExceptionEnum.SERVER_ERROR.getCode(), message);
    }

    @ExceptionHandler(value = {Exception.class,RuntimeException.class, BizCheckException.class})
    @ResponseBody
    public ResponseEntity<JSONObject> resolveException(Exception ex, Locale locale) {
        log.error("exception info : {}, {}", ExceptionUtils.getRootCauseMessage(ex), ex);
        //如果是BizCheckException就需要特殊化处理
        if(ex instanceof  BizCheckException){ //业务异常
            BizCheckException bizCheckException= (BizCheckException) ex;
            return getCustomMessage(String.valueOf(bizCheckException.getCode()),bizCheckException.getMessage());
        }
        //调用异常
        if (ex instanceof NoHandlerFoundException) {// 404无此服务
            String url = ((NoHandlerFoundException) ex).getRequestURL();
            return getErrorMessage(SC_NOT_FOUND, "无此地址：" + url);
        } else if (ex instanceof MissingServletRequestParameterException) {// 400请求参数错误
            String parameterName = ((MissingServletRequestParameterException) ex).getParameterName();
            return getErrorMessage(SC_BAD_REQUEST, "缺少参数：" + parameterName);
        } else if (ex instanceof ServletRequestBindingException) {
            String parameterName = ex.getMessage();
            return getErrorMessage(SC_BAD_REQUEST, "缺少参数：" + parameterName);
        } else if (ex instanceof HttpRequestMethodNotSupportedException) {// 405请求方式不支持
            String method = ((HttpRequestMethodNotSupportedException) ex).getMethod();
            return getErrorMessage(SC_METHOD_NOT_ALLOWED, "不支持："+ method);
        } else if (ex instanceof BindException) {
            String message = this.getBindExceptionMessage(((BindException) ex));
            return getErrorMessage(SC_BAD_REQUEST, message);
        } else if (ex instanceof MethodArgumentNotValidException) {
            BindingResult bindingResult = ((MethodArgumentNotValidException) ex).getBindingResult();
            String message = this.getBindExceptionMessage(bindingResult);
            return getErrorMessage(SC_BAD_REQUEST, message);
        } else if (ex instanceof HttpMessageNotReadableException) {
            Throwable t = ex.getCause();
            if (t instanceof UnrecognizedPropertyException) {
                UnrecognizedPropertyException upe = (UnrecognizedPropertyException) t;
                String propertyName = upe.getPropertyName();
                return getErrorMessage(SC_BAD_REQUEST, (BizExceptionEnum.PARAM_NOT_EXISTS.getMessage(propertyName)));
            } else if (t instanceof InvalidFormatException) {
                InvalidFormatException ife = (InvalidFormatException) t;
                String pathReference = ife.getPathReference();
                int last = pathReference.lastIndexOf("\"");
                String pathReferenceSub = pathReference.substring(0, last);
                int last2 = pathReferenceSub.lastIndexOf("\"");
                String fieldName = pathReference.substring(last2 + 1, last);
                return getErrorMessage(SC_BAD_REQUEST, (BizExceptionEnum.PARAM_TYPE_ILL.getMessage(fieldName)));
            } else if (t instanceof JsonMappingException) {
                JsonMappingException jsonMappeingException = ((JsonMappingException) t);
                List<JsonMappingException.Reference> references = jsonMappeingException.getPath();
                if(CollectionUtils.isEmpty(references)) {
                    return getErrorMessage(SC_BAD_REQUEST, (BizExceptionEnum.PARAM_TURN_EX.getMessage()));
                }
                JsonMappingException.Reference reference = references.get(0);
                if (reference != null) {
                    String propertyName = reference.getFieldName();
                    return getErrorMessage(SC_BAD_REQUEST, (BizExceptionEnum.PARAM_TURN_EX.getMessage(propertyName)));
                }
            } else if (t instanceof JsonParseException) {
                // json格式解析异常
                return getErrorMessage(SC_BAD_REQUEST, BizExceptionEnum.PARAM_FORMAT_EX.getMessage());
            }
        }
        //默认异常
        return getDefaultMessage(ex);
    }

    private String getBindExceptionMessage(BindingResult bindingResult) {
        return bindingResult.getFieldError().getDefaultMessage();
    }

    private static ResponseEntity<JSONObject> getErrorMessage(int status, String text) {
        JSONObject responseJson=new JSONObject();
        responseJson.put(KEY_MESSAGE, text);
        responseJson.put(KEY_CODE,  status);
        ResponseEntity<JSONObject> exceptionRet=new ResponseEntity<JSONObject>(responseJson, httpHeaders, HttpStatus.valueOf(status));
        return	exceptionRet;
    }

    private static ResponseEntity<JSONObject> getCustomMessage(String status, String text) {
        JSONObject responseJson=new JSONObject();
        responseJson.put(KEY_MESSAGE, text);
        responseJson.put(KEY_CODE,  status);
        ResponseEntity<JSONObject> exceptionRet=new ResponseEntity<JSONObject>(responseJson, httpHeaders, HttpStatus.INTERNAL_SERVER_ERROR);
        return	exceptionRet;
    }

    private static ResponseEntity<JSONObject> getDefaultMessage(Exception ex) {
        JSONObject responseJson=new JSONObject();
        responseJson.put(KEY_CODE,BizExceptionEnum.UNKOUN_EEROR.getErrorCode());
        responseJson.put(KEY_MESSAGE,BizExceptionEnum.UNKOUN_EEROR.getMessage());
        responseJson.put("rootCause",ExceptionUtils.getRootCauseMessage(ex));
        ResponseEntity<JSONObject> exceptionRet=new ResponseEntity<JSONObject>(responseJson, httpHeaders, HttpStatus.INTERNAL_SERVER_ERROR);
        return	exceptionRet;
    }
}
